﻿#ifndef NETWORK_H
#define NETWORK_H
#include <QApplication>
#include "NetWork_global.h"
#include <QTcpServer>
#include <QAbstractSocket>
#include <QMutexLocker>
#include <QSemaphore>
#include <ThreadCin.h>
class ThreadClienNetWork;

class NETWORK_EXPORT NetWork : public QApplication {
Q_OBJECT;
private:
	// 输出绑定
	// 绑定输出到多个客户端
	QVector<ThreadClienNetWork*> targetObjs;
	// 客户端输出锁
	QMutex* ioMutex = Q_NULLPTR;
	// 允许连接多个服务端口
	QVector<QTcpSocket*> clienConnectVector;
	// 允许创建服务端
	QTcpServer* serverInstance = Q_NULLPTR;
private:
	// 环境
	QString currentExeName;
	QHash<QString, QVector<QString>> parameter;
	QMultiHash<QString, QString> eventMap;
	ThreadCin* threadCin = Q_NULLPTR;
public:
	QString getCurrentExeName( ) const {
		return currentExeName;
	}

	void setCurrentExeName(const QString& currentExeName) {
		this->currentExeName = currentExeName;
	}

	QHash<QString, QVector<QString>> getParameter( ) const {
		return parameter;
	}

	void setParameter(const QHash<QString, QVector<QString>>& parameter) {
		this->parameter = parameter;
	}

	QMultiHash<QString, QString> getEventMap( ) const {
		return eventMap;
	}

	void setEventMap(const QMultiHash<QString, QString>& eventMap) {
		this->eventMap = eventMap;
	}

protected:
	bool event(QEvent*) override;
public:
	NetWork(int& argc
		, char** argv
		, int i = ApplicationFlags);
	~NetWork( );
	void appRunParameter(QString& key
		, QVector<QString>& value);
	void initClientSocket(QTcpSocket* clienInstance
		, const QString& ip
		, const QString& prot
		, int& iProt);
	int runNetWork( );
public:
	// 信号槽
	void serverNewConnection( );
	void serverAcceptError(QAbstractSocket::SocketError socketError);
	// 客户端
	void clientHostFound( );
	void clientConnected( );
	void clientDisconnected( );
	void clientStateChanged(QAbstractSocket::SocketState);
	void clientError(QAbstractSocket::SocketError);
	void readyRead( );
	// 输入
	void getCin(QString* str
		, QSemaphore* qSemaphore);
	// 输出
};
#endif // NETWORK_H
